import requests
import threading
import time
import json
import random

# 请求的URL
url = "http://127.0.0.1:5000/translate/translate"

# 用户ID列表
user_ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 请求的文本
text = "今天是个好日子"

# 存储每个请求的响应时间
response_times = []

# 模拟请求的函数
def make_requests(user_id):
    for _ in range(20):  # 每个用户发送20次请求
        start_time = time.time()
        try:
            response = requests.post(
                url,
                json={
                    "userId": user_id,
                    "text": text
                }
            )
            response.raise_for_status()  # 检查请求是否成功
            end_time = time.time()
            response_time = end_time - start_time
            response_times.append({
                "user_id": user_id,
                "request_id": _ + 1,
                "response_time": response_time,
                "status_code": response.status_code,
                "response": response.json()
            })
            print(f"User {user_id} - Request {_ + 1} - Response Time: {response_time:.2f} seconds")
        except requests.exceptions.RequestException as e:
            print(f"User {user_id} - Request {_ + 1} - Error: {e}")
            response_times.append({
                "user_id": user_id,
                "request_id": _ + 1,
                "response_time": None,
                "status_code": None,
                "error": str(e)
            })

# 创建线程
threads = []
for user_id in user_ids:
    thread = threading.Thread(target=make_requests, args=(user_id,))
    threads.append(thread)
    thread.start()

# 等待所有线程完成
for thread in threads:
    thread.join()

# 将结果写入JSON文件
with open("../test_results.json", "w", encoding="utf-8") as f:
    json.dump(response_times, f, ensure_ascii=False, indent=4)

# 输出测试结果
print("\nTest Results:")
print(f"Total Requests: {len(response_times)}")
success_requests = [rt for rt in response_times if rt["response_time"] is not None]
failed_requests = [rt for rt in response_times if rt["response_time"] is None]
print(f"Successful Requests: {len(success_requests)}")
print(f"Failed Requests: {len(failed_requests)}")

# 计算平均响应时间
if success_requests:
    avg_response_time = sum(rt["response_time"] for rt in success_requests) / len(success_requests)
    print(f"Average Response Time: {avg_response_time:.2f} seconds")

# 输出每个请求的详细信息
print("\nDetailed Results:")
for rt in response_times:
    print(f"User {rt['user_id']} - Request {rt['request_id']}:")
    if rt["response_time"] is not None:
        print(f"  Response Time: {rt['response_time']:.2f} seconds")
        print(f"  Status Code: {rt['status_code']}")
        print(f"  Translated Text: {rt['response'].get('translated_text', 'N/A')}")
    else:
        print(f"  Error: {rt['error']}")